package cn.edu.niit.studyspace.activity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import cn.edu.niit.studyspace.R;
import cn.edu.niit.studyspace.adapter.MusicAdapter;
import cn.edu.niit.studyspace.bean.Music;
import cn.edu.niit.studyspace.service.MusicService;
import cn.edu.niit.studyspace.util.HttpUtil;

public class MusicActivity extends AppCompatActivity implements MusicAdapter.OnItemClick {

  boolean isPlaying = false; // 音乐开始播放状态

  boolean isPause = false; // 音乐暂停状态

  RecyclerView rv_musics;

  TextView mMusicName;
  TextView mMusicAuthor;
  TextView mMusicAlbum;
  ImageView mAlbumPic;

  List<Music> musics = new ArrayList<>();

  // 将list与适配器绑定
  MusicAdapter musicAdapter = new MusicAdapter(this, musics, this);
  private ServiceConnection conn =
      new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
          musicService = ((MusicService.MusicServiceBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {}
      };

  private MusicService musicService;
  // 当前播放音乐
  private Music music;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_music);
    getSupportActionBar().setTitle("音乐播放器");
    // 初始化view
    initView();
    // 加载数据
    initData();
    // 绑定service
    initService();
  }

  private void initService() {
    bindService(new Intent(MusicActivity.this, MusicService.class), conn, Service.BIND_AUTO_CREATE);
  }

  private void initData() {
    // 发送请求地址
    HttpUtil.sendGetRequest(
        "http://tingapi.ting.baidu"
            + ".com/v1/restserver/ting?method=baidu"
            + ".ting.billboard"
            + ".billList&type=2&size=40&offset=0",
        new HttpUtil.HttpCallbackListener() {
          @Override
          public void onFinish(String response) { // 网络请求成功
            musics =
                JSON.parseArray(
                    JSON.parseObject(response).getJSONArray("song_list").toString(), Music.class);

            runOnUiThread(
                new Runnable() { // 开启线程
                  @Override
                  public void run() {
                    // 将music添加至musicAdapter
                    musicAdapter.notifyData(musics);
                  }
                });
          }

          @Override
          public void onError(final Exception e) { // 网络请求失败

            runOnUiThread(
                new Runnable() { // 开启线程

                  @Override
                  public void run() {
                    // 提示请求失败
                    Log.e("请求错误:-->>", e.getMessage());
                    Toast.makeText(MusicActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                  }
                });
          }
        });
  }

  private void initView() {
    mMusicName = findViewById(R.id.tv_music_name);
    mMusicAuthor = findViewById(R.id.tv_music_author);
    mMusicAlbum = findViewById(R.id.tv_music_album);
    mAlbumPic = findViewById(R.id.iv_music_pic);
    // 1.初始化控件
    rv_musics = findViewById(R.id.rv_music);
    // 2.给ListView设置Adapter
    rv_musics.setAdapter(musicAdapter);
  }

  @Override
  protected void onStop() {
    super.onStop();
    unbindService(conn);
  }

  public void rev(View view) {
    musicService.rev();
  }

  public void play(View view) {
    // 判断状态
    if (view == null) {
      isPlaying = false;
      isPause = false;
    }

    if (isPlaying) {
      // 暂停，更新图标
      ((ImageView) findViewById(R.id.iv_music_play)).setImageResource(R.drawable.ic_play);
      // 调用方法将正在模仿的音乐暂停
      musicService.pause();
      // 设置状态
      isPause = true;
      isPlaying = false;
    } else {
      // 播放
      if (isPause) { // 点击继续播放
        // 调用方法继续播放音乐
        musicService.restart();
        // 设置状态
        isPause = false;
      } else {
        // 重新加载音乐
        musicService.play(music.getSong_id());
      }
      ((ImageView) findViewById(R.id.iv_music_play)).setImageResource(R.drawable.ic_pause);
      isPlaying = true;
    }
  }

  public void ffw(View view) {
    musicService.ffw();
  }

  public void reload(View view) {
    musicService.reload(music.getSong_id());
  }

  @Override
  public void onItemClick(View view, int position) {
    music = musics.get(position);
    mMusicAlbum.setText(music.getAlbum_title());
    mMusicAuthor.setText(music.getArtist_name());
    mMusicName.setText(music.getTitle());
    Glide.with(MusicActivity.this).load(music.getPic_small()).into(mAlbumPic);
    play(null);
  }
}
